<template>
	<view class="chat-room flex flex-col h-full bg-white">
		<NavBarVue :title="nickname"></NavBarVue>
		<view class="flex-1 room-content overflow-hidden" @click="hideBtns">
			<scroll-view scroll-y="true" class="h-full" :scroll-into-view="scrollIntoViewId" @scrolltoupper="getMessageList">
				<view class="chat-list">
					<view class="flex" :style="{ justifyContent: getJustifyContentVal(e) }" v-for="e,i in chatList" :key="i">
						<!-- 用户 -->
						<view class="chat-item-other" v-if="params.userId !=e.from">
							<view class="chat-item-left">
								<ImageBoxVue :src="headimg" width="100rpx" height="100rpx"></ImageBoxVue>
							</view>
							<view class="chat-item-right">
								<view class="mb-10">
									<text class="f-s-28 c-333">{{ nickname }}</text>
									<text class="right-role f-s-24 c-666">{{ e.role }}</text>
								</view>
								<view class="right-msg f-s-28 c-fff">
									<ChatBoxVue @scrollToBottom="scrollToBottom" @look-Img="lookImg" :msgInfo="e" :tim="tim"
										:val="e.payload">
									</ChatBoxVue>
								</view>
							</view>
						</view>
						<!-- 自己 -->
						<view class="chat-item-self items-start" v-if="params.userId ==e.from">
							<view class="chat-item-left">
								<ImageBoxVue :src="user.headimg" width="100rpx" height="100rpx"></ImageBoxVue>
							</view>
							<view class="chat-item-right">
								<view class="mb-10 t-align-r">
									<text class="f-s-28 c-333">{{ user.nickname }}</text>
									<text class="right-role f-s-24 c-666">{{ e.role }}</text>
								</view>
								<view class="right-msg f-s-28 c-fff">
									<ChatBoxVue @scrollToBottom="scrollToBottom" @look-Img="lookImg" :msgInfo="e" :tim="tim"
										:val="e.payload">
									</ChatBoxVue>
								</view>
							</view>
						</view>
						<!-- 时间 -->
						<view class="chat-item-time f-s-22 c-666" v-if="e.type === 'time'">{{ e.content }}</view>
					</view>
				</view>
				<view id="lastItem"></view>
			</scroll-view>
		</view>
		<!-- 查看图片 -->
		<view class="position-fixed top-0 left-0 right-0 bottom-0 flex flex-col items-center justify-center" v-if="imgUrl"
			@click="imgUrl=''" style="width:750rpx;background-color:#000;z-index: 999;"
			:style="{height:`${windowInfo.windowHeight}px`}">
			<uv-image :src="imgUrl" width="100%" height="100%" mode="aspectFit"></uv-image>
		</view>

		<chatFooterVue ref="chatFootRef" @scrollToBottom="scrollToBottom" @confirm="sendContent"
			@createCustomMessage="createCustomMessage"></chatFooterVue>
	</view>
</template>

<script setup>
	import {
		nextTick,
		ref
	} from 'vue'
	import {
		onShow,
		onHide,
		onLoad
	} from '@dcloudio/uni-app'
	import ChatBoxVue from './components/ChatBox.vue';
	import chatFooterVue from './components/chatFooter.vue'
	import TencentCloudChat from '@tencentcloud/chat';
	import {
		tim
	} from "@/apis/IM.js"
	import liveApi from '@/apis/apiList/liveApi';
	import permision from "@/static/permission.js"
	import dayjs from "dayjs"
	const footer = ref({
		showBtns: false
	})
	const imgUrl = ref("")
	const scrollIntoViewId = ref('')
	const nickname = ref('')
	const chatFootRef = ref()
	const headimg = ref('')
	let conversationID = ""
	let fromAccount = ""
	const windowInfo = uni.getWindowInfo()
	const user = ref(uni.getStorageSync('user'))
	const chatList = ref([])
	onLoad(e => {
		permision.requestAndroidPermission(["android.permission.RECORD_AUDIO", "android.permission.CAMERA",
			"android.permission.READ_EXTERNAL_STORAGE"
		])
		console.log(e);
		if (e.conversationID) {
			// 通过聊天列表进入
			conversationID = e.conversationID
			nickname.value = e.nickname
			headimg.value = e.headimg
			fromAccount = e.fromAccount
		} else {
			//首次私聊
			nickname.value = e.nickname
			headimg.value = e.headimg
			fromAccount = e.fromAccount
		}
		nextTick(() => {
			chatFootRef.value.onInit(e)
		})
		// getuserSig()
		// tim.on(TencentCloudChat.EVENT.SDK_READY, function(event) {
		// console.log('初始化成功，开始监听', event);
		chaton()
		// })
	})
	const hideBtns = () => {
		chatFootRef.value.showBtns = false
	}
	const lookImg = (e) => {
		console.log(e);
		imgUrl.value = e
	}
	const params = ref({
		sdkAppId: 1400752704, // Please replace with your own sdkAppId
		userId: `${uni.getStorageSync('user').id}`, //用户 ID
		userSig: "",
	});
	// 获取用户签名
	// const getuserSig = () => {
	// 	liveApi.membergetLiveTokens({
	// 		id: params.value.userId
	// 	}).then(res => {
	// 		params.value.userSig = res.data.code
	// 		startChat()
	// 	})
	// }
	onHide(() => {
		// tim.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg)
	})
	let nextReqMessageID = ""
	// 获取聊天记录
	const getMessageList = async () => {
		const res = await tim.getMessageList({
			conversationID: conversationID || `C2C${fromAccount}`,
			nextReqMessageID: nextReqMessageID || undefined
		})
		// .then(res => {
		console.log(res);
		await res.data.messageList.forEach(a => {
			if (a.payload.description && a.payload.description.indexOf('***') !== -1) {
				a.payload.description = a.payload.description.split('***')[1]
			}
			if (nextReqMessageID == '') {
				setMsg(a)
				setTimeout(() => {
					scrollToBottom()
				}, 500)
			} else {
				setMsg(a, 'unshift')

			}

		})

		nextReqMessageID = res.data.nextReqMessageID

		// })
	}
	// 滚动至聊天底部  
	const scrollToBottom = () => {
		// if (nextReqMessageID == '') {
		scrollIntoViewId.value = 'lastItem'
		nextTick(() => {
			scrollIntoViewId.value = ""
		})
		// }
	}


	const chaton = () => {
		if (conversationID) {
			tim.setMessageRead({
				'conversationID': conversationID
			}) //设置已读
		}
		getMessageList()
		// 
		// 监听会话列表
		tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg);
	}
	const getMsg = (e) => {
		console.log('收到消息', e);
		let obj = e.data[0]
		setMsg(obj)

	}
	const addChatList = (obj, type) => {
		if (type && type == 'unshift')
			chatList.value.unshift(obj)
		else
			chatList.value.push(obj)
	}
	const setMsg = (obj, type) => {
		if (obj.type == 'TIMTextElem') {
			// 消息
			obj.payload.data = 'text'
			addChatList(obj, type)
		}
		if (obj.type == 'TIMCustomElem') {
			// 自定义
			if (obj.payload.data == 'img') addChatList(obj, type)
			if (obj.payload.data == 'astrolabe') addChatList(obj, type)
			if (obj.payload.data == 'audio') addChatList(obj, type)
			if (obj.payload.data == 'gift' || obj.payload.data == 'answer') addChatList({
				...obj,
				payload: {
					...obj.payload,
					description: JSON.parse(obj.payload.description)
				}
			}, type)
		}
		if (type !== 'unshift')
			nextTick(() => {
				scrollToBottom()
			})
	}
	// 获取排列方式
	const getJustifyContentVal = (val) => {
		if (!val.from) return 'center'
		if (val.from == params.value.userId) return 'flex-end'
		else return 'flex-start'
	}
	// 发送内容
	const sendContent = (content) => {
		const payload = {
			text: content
		}
		console.log('发送消息', fromAccount, payload);
		const message = tim.createTextMessage({
			to: fromAccount,
			conversationType: TencentCloudChat.TYPES.CONV_C2C,
			payload: payload,
		});
		console.log(message);
		tim.sendMessage(message);
		getMsg({
			data: [{
				from: params.value.userId,
				type: "TIMTextElem",
				time: dayjs().unix(),
				payload: payload
			}]
		})
	}
	// 发送自定义信息 data:类型；description：信息；extension：自定义
	const createCustomMessage = (payload) => {
		console.log('发送自定义信息', fromAccount, payload);
		const message = tim.createCustomMessage({
			to: fromAccount,
			conversationType: TencentCloudChat.TYPES.CONV_C2C,
			payload: payload,
		});
		tim.sendMessage(message);
		getMsg({
			data: [{
				from: params.value.userId,
				type: "TIMCustomElem",
				time: dayjs().unix(),
				payload: payload
			}]
		})
	}
</script>

<style lang="scss" scoped>
	.chat-room {

		.room-content {
			.chat-list {
				padding: 30rpx;
				box-sizing: border-box;

				.chat-item-other,
				.chat-item-self {
					display: flex;
					margin-bottom: 60rpx;

					.chat-item-left {
						width: 60rpx;
						min-width: 60rpx;
						height: 60rpx;
						min-height: 60rpx;
						border-radius: 50%;
						overflow: hidden;
						margin-right: 10rpx;
					}

					.chat-item-right {
						.right-role {
							// border-left: 2rpx solid #999;
							padding-left: 10rpx;
							margin-left: 10rpx;
						}

						.right-msg {
							border-top-right-radius: 20rpx;
							border-bottom-right-radius: 20rpx;
							border-bottom-left-radius: 20rpx;
							background: rgb(245, 246, 248);
						}
					}
				}

				.chat-item-self {
					flex-direction: row-reverse;

					.chat-item-left {
						margin-left: 10rpx;
					}

					.right-msg {
						border-top-left-radius: 20rpx;
						border-top-right-radius: 0 !important;
						background-color: rgb(245, 246, 248) !important;
					}
				}

				.chat-item-time {
					text-align: center;
					margin-bottom: 60rpx;
				}
			}
		}
	}
</style>